/**
 * Copyright (C), 2001-2031, www.bosssof.com.cn
 * FileName: SentinelConfig.java
 * Author: YuXingZh
 * Date: 15/6/2024 上午9:05
 * Description:
 * <p>
 * History:
 * Date          Author   Version  Desc
 * 2024-01-01    bosssoft  1.0.0   initialize this file
 */
package com.bosssoft.g1.gateway.component;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.aspectj.SentinelResourceAspect;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

/**
 * @className: SentinelConfig
 * @description:
 * 解决什么问题：
 *  演示线程池的正确使用 
 * 主要方法和数据成员：
 *  methodxx 使用 ThreadPoolExecutor创建线程进行任务操作
 * 注意事项：
 *  例如：该类需要从容器获取不可以new   
 * @author: YuXingZh
 * @date: 15/6/2024上午9:05
 * @since 1.0
 **/
@Configuration
public class SentinelConfig {

    @PostConstruct
    public void init() {
        List<FlowRule> rules = new ArrayList<>();
        FlowRule rule = new FlowRule();
        rule.setResource("GLOBAL_LIMIT_RESOURCE"); // 自定义的资源名称
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        rule.setCount(2); // 每秒最多 10 个请求
        rules.add(rule);
        FlowRuleManager.loadRules(rules);

        // 熔断规则
        List<DegradeRule> degradeRules = new ArrayList<>();
        DegradeRule degradeRule = new DegradeRule();
        degradeRule.setResource("GLOBAL_CIRCUIT_BREAKER");
        degradeRule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT); // 错误数
        degradeRule.setCount(4); // 每秒最多3次错误请求则熔断
        degradeRule.setMinRequestAmount(4); // 设置最小请求数
        degradeRule.setTimeWindow(2); // 熔断时长，单位为秒
        degradeRules.add(degradeRule);
        DegradeRuleManager.loadRules(degradeRules);
    }

    @Bean
    public SentinelResourceAspect sentinelResourceAspect() {
        return new SentinelResourceAspect();
    }
}